<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="68px" style="display: flex; justify-content: flex-end;">
      <el-form-item label="老人姓名" prop="elderName">
        <el-input
          v-model="queryParams.elderName"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="体检日期" prop="examDate">
        <el-date-picker
          v-model="queryParams.examDate"
          type="daterange"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @keyup.enter.native="handleQuery">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checkupInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="老人姓名" align="center" prop="elderName" fixed show-overflow-tooltip/>
      <el-table-column label="血糖数值" align="center" prop="bloodSugar" fixed show-overflow-tooltip/>
      <el-table-column label="血压" align="center" prop="bloodPressure" fixed show-overflow-tooltip/>
      <el-table-column label="血常规" align="center" prop="bloodRoutine" fixed show-overflow-tooltip/>
      <el-table-column label="尿常规" align="center" prop="urinalysis" fixed show-overflow-tooltip/>
      <el-table-column label="心电图数据" align="center" prop="ecg" fixed show-overflow-tooltip/>
<!--      <el-table-column label="骨密度" align="center" prop="boneDensity" fixed show-overflow-tooltip/>-->
      <el-table-column label="体检日期" align="center" prop="examDate" fixed show-overflow-tooltip/>
      <el-table-column label="心率" align="center" prop="heartRate" fixed show-overflow-tooltip/>
      <el-table-column label="健康状况" align="center" prop="healthStatus" fixed show-overflow-tooltip/>
<!--      <el-table-column label="疾病类型" align="center" prop="diseaseType" fixed show-overflow-tooltip/>-->
      <el-table-column label="健康评分" align="center" prop="healthScore" fixed show-overflow-tooltip/>
      <el-table-column label="体检医生" align="center" prop="doctorName" fixed show-overflow-tooltip/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改老人健康体检对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px" :disabled="isDisabled">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="老人姓名" prop="elderId">
              <el-select v-model="form.elderId" filterable placeholder="请选择">
                <el-option
                  v-for="item in elderInfoList"
                  :key="item.elderId"
                  :label="item.elderName"
                  :value="item.elderId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="血糖数值" prop="bloodSugar">
              <el-input v-model="form.bloodSugar" placeholder="请输入血糖数值" />
            </el-form-item>
            <el-form-item label="血压" prop="bloodPressure">
              <el-input v-model="form.bloodPressure" placeholder="请输入血压" />
            </el-form-item>
            <el-form-item label="血常规" prop="bloodRoutine">
              <el-input v-model="form.bloodRoutine" placeholder="请输入血常规" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="尿常规" prop="urinalysis">
              <el-input v-model="form.urinalysis" placeholder="请输入尿常规" />
            </el-form-item>
            <el-form-item label="心率" prop="heartRate">
              <el-input v-model="form.heartRate" placeholder="请输入心率" />
            </el-form-item>
            <el-form-item label="心电图数据" prop="ecg">
              <el-input type="textarea"
                        :rows="2" maxlength="200" v-model="form.ecg" placeholder="请输入心电图数据" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="体检日期" prop="examDate">
              <el-date-picker
                v-model="form.checkTime"
                type="date"
                placeholder="选择日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="健康状态" prop="healthStatus">
              <el-input type="textarea"
                        :rows="2" maxlength="200" v-model="form.healthStatus" placeholder="请输入健康状态" />
            </el-form-item>
            <el-form-item label="健康评分" prop="healthScore">
              <el-input-number v-model="form.healthScore"  :min="1" :max="100" label="健康评分" size="mini"></el-input-number>
              <el-tag type="info" size="mini">评分范围：1~100</el-tag>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="8">
            <el-form-item label="体检人员" prop="doctorId">
              <el-select v-model="form.doctorId" filterable placeholder="请选择">
                <el-option
                  v-for="item in memberInfoList"
                  :key="item.memberId"
                  :label="item.memberName"
                  :value="item.memberId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" >
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCheckupInfo, getCheckupInfo, delCheckupInfo, addCheckupInfo, updateCheckupInfo } from "@/api/business/checkupInfo";
import {getElderInfoByName, listAllElderInfo} from "@/api/business/elderInfo";
import {getMemberInfoList} from "@/api/business/memberInfo";

export default {
  name: "CheckupInfo",
  data() {
    return {
      isDisabled:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 老人健康体检表格数据
      checkupInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        elderId: null,
        bloodSugar: null,
        bloodPressure: null,
        bloodRoutine: null,
        urinalysis: null,
        ecg: null,
        boneDensity: null,
        examDate: null,
        heartRate: null,
        healthStatus: null,
        isAbnormal: null,
        diseaseType: null,
        healthScore: null,
        doctorId: null,
        createUserId: null,
        updateUserId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        elderId: [
          { required: true, message: "老人姓名不能为空", trigger: "blur" }
        ],
        healthScore: [
          { required: true, message: "健康评分不能为空", trigger: "blur" }
        ],
      },
      restaurants: [],
      state: '',
      timeout:  null,
      elderInfoList:{},
      memberInfoList:{},
    };
  },
  created() {
    this.getList();
    this.getElderInfoList();
    this.getMemberInfoList();
  },
  methods: {
    /** 查询老人健康体检列表 */
    getList() {
      this.loading = true;
      if(this.queryParams.examDate != null) {
        const time = this.queryParams.examDate;
        this.queryParams.startTime = time[0];
        this.queryParams.endTime = time[1]
      }
      listCheckupInfo(this.queryParams).then(response => {
        this.checkupInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        elderId: null,
        bloodSugar: null,
        bloodPressure: null,
        bloodRoutine: null,
        urinalysis: null,
        ecg: null,
        boneDensity: null,
        examDate: null,
        heartRate: null,
        healthStatus: null,
        isAbnormal: null,
        diseaseType: null,
        healthScore: null,
        doctorId: null,
        createUserId: null,
        createTime: null,
        updateUserId: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加老人健康体检";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCheckupInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.isDisabled = true;
        this.title = "修改老人健康体检";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // updateCheckupInfo(this.form).then(response => {
            //   this.$modal.msgSuccess("修改成功");
            //   this.open = false;
            //   this.getList();
            // });
          } else {
            addCheckupInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除老人健康体检编号为"' + ids + '"的数据项？').then(function() {
        return delCheckupInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/checkupInfo/export', {
        ...this.queryParams
      }, `checkupInfo_${new Date().getTime()}.xlsx`)
    },
    // querySearchAsync(queryString, cb) {
    //   let results = []
    //   if (queryString) {
    //     const findout = this.elderInfoList.elderId.value.filter((x) => this.nameFilter(x, queryString))
    //     results = findout.map(x => ({ ...x, value: x.label }))
    //   } else {
    //     results = this.elderInfoList.elderId.value.map(x => ({ ...x, value: x.label }))
    //   }
    //
    //   console.log(results, '结果')
    //   clearTimeout(timeOut)
    //   setTimeout(() => {
    //     cb(results)
    //   }, 1000);
    // },
    // 站线列表数据
    async querySearchAsync(queryString, cd) {
      console.log("queryString, cd",queryString, cd);
      let getStationList = await getElderInfoByName({
        elderName: queryString, //因为给接口的参数已经作为查询条件了，下面就不用再用filter过滤符合条件的数据了
        // city: JSON.parse(localStorage.getItem("userInfo")).userId,
        // standTypeCode: "02",
      });

      console.log(getStationList)
      if (getStationList.status) {
        let substationName = getStationList.rows.map((item) => ({
          value: item.elderId,
        }));  //这里是取出后端数据中所需要的字段并放入到名字为value字段中；必须要这样放，因为官网是使用的value，可以从上面官网看一下

        substationName = queryString ? substationName : [];
        cd(substationName);
      }
    },
    nameFilter(item, queryString){
      return item.label.toLowerCase().match(queryString.toLowerCase()) ? true : false
    },
    handleSelectElder(item) {
      console.log(item);
      console.log(item, '选择结果')
      this.form.elderId.value = "[label：" + item.elderName + "； name：" + item.elderId + "]"
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    getElderInfoList(){
      listAllElderInfo().then(response => {
        this.elderInfoList = response.rows;
      })
    },
    getMemberInfoList() {
      getMemberInfoList().then(response => {
        this.memberInfoList = response.data;
      })
    }
  },
};
</script>
